<script setup>
import seckillActivityApi from '@/api/seckill/seckillActivity_api.js'
import { ref, onMounted } from "vue"
import { ElMessageBox, ElMessage } from "element-plus"
import lodash from 'lodash'

//定义绑定的数据
//表格中的数据
const tableData = ref([]);
const total = ref(0);
//定义对话框的显示状态
const editWinVisible = ref(false);
const addWinVisible = ref(false);

//查询数据
const searchObj = ref({
  current: 1,
  limit: 10,
  name: '',
  start_time: '',
  end_time: '',
  status: '',
});

//要修改或者新增的数据
const obj = ref({});

const search = async () => {
  try {
    console.log('发送的查询参数:', searchObj.value);
    var result = await seckillActivityApi.getActivityPage(
        searchObj.value.current,
        searchObj.value.limit,
        searchObj.value
    );
    console.log('收到的响应数据:', result);

    // 检查返回的数据结构
    if (result && typeof result === 'object') {
      // 如果返回的是直接的分页数据
      if (result.records && Array.isArray(result.records)) {
        tableData.value = result.records;
        total.value = result.total || 0;
      }
      // 如果返回的是包含data字段的对象（Result包装）
      else if (result.data && result.data.records && Array.isArray(result.data.records)) {
        tableData.value = result.data.records;
        total.value = result.data.total || 0;
      }
      // 其他情况
      else {
        tableData.value = [];
        total.value = 0;
      }
    } else {
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取秒杀活动列表时出错:', error);
    if (error.response) {
      if (error.response.status === 404) {
        ElMessage.error('API接口未找到，请检查后端服务是否正常运行且API路径配置正确');
      } else if (error.response.status === 500) {
        ElMessage.error('服务器内部错误，请联系管理员');
      } else {
        ElMessage.error(`请求失败: ${error.response.status} ${error.response.statusText}`);
      }
    } else if (error.request) {
      ElMessage.error('无法连接到服务器，请检查网络连接和后端服务是否运行');
    } else {
      ElMessage.error('请求失败: ' + error.message);
    }
    tableData.value = [];
    total.value = 0;
  }
}

//页面加载后要挂载的数据
onMounted(async () => {
  await search();
});

//重置查询条件
const resetSearch = () => {
  searchObj.value.name = '';
  searchObj.value.start_time = '';
  searchObj.value.end_time = '';
  searchObj.value.status = '';
  searchObj.value.current = 1;
  search();
}

//分页查询用
const handleSizeChange = () => {
  search();
}

//分页查询用
const handleCurrentChange = () => {
  search();
}

//定义方法
const handlerSearch = () => {
  searchObj.value.current = 1;
  search();
}

const handlerAdd = () => {//添加
  obj.value = {};
  addWinVisible.value = true;//打开对话框
}

//新增对话框的取消按钮点击事件
const addCancel = () => {
  obj.value = {};//清空数据
  addWinVisible.value = false;//关闭新增对话框
}

//编辑对话框的取消按钮点击事件
const editCancel = () => {
  obj.value = {};//清空数据
  editWinVisible.value = false;//关闭对话框
}

//编辑对话框的提交按钮点击事件
const editCommit = async () => {
  try {
    const result = await seckillActivityApi.updateActivity(obj.value);//提交修改数据
    console.log('编辑返回结果:', result);

    if (result && (result.code === 200 || !result.code)) {
      ElMessage.success('更新成功');
      await search();//刷新表格
      editWinVisible.value = false;//关闭编辑对话框
    } else {
      ElMessage.error(result?.message || '更新失败');
    }
  } catch (error) {
    console.error('更新失败:', error);
    ElMessage.error('更新失败: ' + (error.response?.data || error.message));
  }
}

//新增对话框的提交按钮点击事件
const addCommit = async () => {
  try {
    // 验证必填字段
    if (!obj.value.name) {
      ElMessage.error('请输入活动名称');
      return;
    }
    if (!obj.value.start_time) {
      ElMessage.error('请选择开始时间');
      return;
    }
    if (!obj.value.end_time) {
      ElMessage.error('请选择结束时间');
      return;
    }

    // 确保时间格式正确
    let start_time = obj.value.start_time;
    let end_time = obj.value.end_time;

    // 如果是日期对象，则转换为字符串
    if (start_time instanceof Date) {
      start_time = formatDate(start_time);
    }
    if (end_time instanceof Date) {
      end_time = formatDate(end_time);
    }

    // 构造发送给后端的数据
    const requestData = {
      name: obj.value.name,
      start_time: start_time,
      end_time: end_time,
      status: obj.value.status !== undefined ? parseInt(obj.value.status) : 0
    };

    console.log('发送的新增数据:', requestData);

    // 使用现有的API方法发送请求
    const result = await seckillActivityApi.addActivity(requestData);

    // 检查返回结果
    if (result && (result.code === 200 || result.code === undefined)) {
      console.log('请求成功:', result);
      ElMessage.success('添加成功');
      await search();
      addWinVisible.value = false;
    } else {
      ElMessage.error(result?.msg || result?.message || '添加失败');
    }
  } catch (error) {
    console.error('请求失败:', error);
    if (error.response) {
      console.error('响应状态:', error.response.status);
      console.error('响应头:', error.response.headers);

      if (error.response.data) {
        console.error('响应数据:', error.response.data);
        if (typeof error.response.data === 'object') {
          ElMessage.error(`添加失败: ${JSON.stringify(error.response.data)}`);
        } else {
          ElMessage.error(`添加失败: ${error.response.data}`);
        }
      } else {
        ElMessage.error(`添加失败: ${error.response.status} ${error.response.statusText}`);
      }
    } else {
      ElMessage.error('网络请求失败: ' + error.message);
    }
  }
}

// 添加日期格式化函数
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const handleEdit = (index, row) => {
  obj.value = lodash.clone(row);
  editWinVisible.value = true;
  console.log(index, row)
}

const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '确认删除该行数据吗? 活动删除后相关秒杀商品也会失效',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(async () => {
        try {
          const result = await seckillActivityApi.deleteActivity(row.id);
          if (result && (result.code === 200 || !result.code)) {
            ElMessage.success('删除成功');
            //重新加载数据
            searchObj.value.current = 1;
            await search();
          } else {
            ElMessage.error(result.message || '删除失败');
          }
        } catch (error) {
          ElMessage.error('删除失败: ' + error.message);
        }
      })
      .catch(() => {
      })
}

// 切换秒杀活动状态
const handleStatusChange = async (row) => {
  try {
    const newStatus = row.status === 1 ? 0 : 1;
    const result = await seckillActivityApi.updateStatus(row.id, newStatus);
    if (result && (result.code === 200 || !result.code)) {
      ElMessage.success(result.message || '状态更新成功');
      await search(); // 刷新表格
    } else {
      ElMessage.error(result.message || '状态更新失败');
    }
  } catch (error) {
    ElMessage.error('状态更新失败: ' + error.message);
  }
}

const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  return dateTimeStr.replace('T', ' ');
}

// 格式化状态显示
const formatStatus = (status) => {
  switch (status) {
    case 0:
      return '未开始';
    case 1:
      return '进行中';
    case 2:
      return '已结束';
    default:
      return '未知状态';
  }
}

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case 0:
      return 'info';
    case 1:
      return 'success';
    case 2:
      return 'danger';
    default:
      return 'info';
  }
}
</script>

<template>
  <div class="seckill-activity-management">
    <h2>秒杀活动管理</h2>

    <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top:10px">
      <el-form-item label="活动名称">
        <el-input
            v-model="searchObj.name"
            placeholder="请输入活动名称"
            clearable
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchObj.status" placeholder="请选择状态" clearable>
          <el-option label="未开始" value="0"></el-option>
          <el-option label="进行中" value="1"></el-option>
          <el-option label="已结束" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlerSearch">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="resetSearch">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlerAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="活动ID"></el-table-column>
      <el-table-column prop="name" label="活动名称"></el-table-column>
      <el-table-column prop="start_time" label="开始时间">
        <template #default="scope">
          <span>{{ formatDateTime(scope.row.start_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="end_time" label="结束时间">
        <template #default="scope">
          <span>{{ formatDateTime(scope.row.end_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ formatStatus(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间">
        <template #default="scope">
          <span>{{ formatDateTime(scope.row.create_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理按钮">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
            编辑
          </el-button>
          <el-button
              size="small"
              :type="scope.row.status === 1 ? 'danger' : 'success'"
              @click="handleStatusChange(scope.row)"
          >
            {{ scope.row.status === 1 ? '结束' : '启用' }}
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :page-sizes="[10,20,30,50]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!--编辑对话框-->
    <el-dialog v-model="editWinVisible" title="编辑秒杀活动" width="500">
      <el-form :model="obj">
        <el-form-item label="活动名称" :label-width="100">
          <el-input v-model="obj.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="开始时间" :label-width="100">
          <el-date-picker
              v-model="obj.start_time"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" :label-width="100">
          <el-date-picker
              v-model="obj.end_time"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" :label-width="100">
          <el-select v-model="obj.status" placeholder="请选择状态">
            <el-option label="未开始" :value="0"></el-option>
            <el-option label="进行中" :value="1"></el-option>
            <el-option label="已结束" :value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editCancel">取消</el-button>
          <el-button type="primary" @click="editCommit">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!--新增对话框-->
    <el-dialog v-model="addWinVisible" title="新增秒杀活动" width="500">
      <el-form :model="obj">
        <el-form-item label="活动名称" :label-width="100">
          <el-input v-model="obj.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="开始时间" :label-width="100">
          <el-date-picker
              v-model="obj.start_time"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" :label-width="100">
          <el-date-picker
              v-model="obj.end_time"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择结束时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addCancel">取消</el-button>
          <el-button type="primary" @click="addCommit">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.seckill-activity-management {
  padding: 20px;
  background-color: #fff;
}

.seckill-activity-management h2 {
  margin-bottom: 20px;
}
</style>
